package com.guet.niit.Login.controller.admin;

import com.guet.niit.Admin.dao.AgentDaolmpl;
import com.guet.niit.Admin.dao.ChargingDaolmpl;
import com.guet.niit.Admin.dao.ChargingPileDaolmpl;
import com.guet.niit.Admin.dao.UserDaolmpl;
import com.guet.niit.Admin.pojo.Agent;
import com.guet.niit.Admin.pojo.Charging;
import com.guet.niit.Admin.pojo.ChargingPile;
import com.guet.niit.Admin.pojo.User;
import com.guet.niit.Login.pojo.StationData;
import com.guet.niit.Login.pojo.StationPileData;
import com.guet.niit.util.adminSwitchoverMenu;
import com.guet.niit.util.exitLogin;
import com.sun.javafx.stage.StageHelper;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

public class ChargingPileManageFxController implements Initializable {
    public static ChargingPileManageFxController chargingPileManageFxController;

    @FXML
    private MenuItem stationManage;

    @FXML
    private MenuItem agentManage;

    @FXML
    private MenuItem userManage;

    @FXML
    private MenuItem mainMenu;

    @FXML
    private MenuItem exit;

    @FXML
    private TableView<StationPileData> tableView;
    private ObservableList<StationPileData> data = FXCollections.observableArrayList();

    @FXML
    private TableColumn<StationPileData, Integer> tc_pileId;

    @FXML
    private TableColumn<StationPileData, String> tc_stationName;

    @FXML
    private TableColumn<StationPileData, Double> tc_servicePower;

    @FXML
    private TableColumn<StationPileData, String> tc_chargingType;

    @FXML
    private TableColumn<StationPileData, Double> tc_serviceCharge;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        chargingPileManageFxController = this;
    }

    /**
     * 通过菜单子项进入充电站管理
     * @param actionEvent
     */
    public void enterStationManageByMenuItem(ActionEvent actionEvent) {
        String text = stationManage.getText();
        adminSwitchoverMenu.backtrack(ChargingPileManageFxController.class,text);
        //调用dao层查询充电站表
        ChargingDaolmpl chargingDao = new ChargingDaolmpl();
        List<Charging> stations = chargingDao.chargingInquire();
        //读取充电站列表信息
        ChargingStationManageFxController.chargingStationManageFxController.readStationsInfo(stations);
    }

    /**
     * 通过菜单子项进入代理商管理
     * @param actionEvent
     */
    public void enterAgentManageByMenuItem(ActionEvent actionEvent) {
        String text = agentManage.getText();
        adminSwitchoverMenu.backtrack(ChargingPileManageFxController.class,text);
        //调用dao层查询代理商表
        AgentDaolmpl agentDao = new AgentDaolmpl();
        List<Agent> agents = agentDao.agentInquire();

        //读取代理商列表信息
        AgentManageFxController.agentManageFxController.readAgentInfo(agents);
    }

    /**
     * 通过菜单子项进入用户管理
     * @param actionEvent
     */
    public void enterUserManageByMenuItem(ActionEvent actionEvent) {
        String text = userManage.getText();
        adminSwitchoverMenu.backtrack(ChargingPileManageFxController.class,text);
        //调用dao层查询用户表
        UserDaolmpl userDao = new UserDaolmpl();
        List<User> users = userDao.userInquire();

        //读取用户列表信息
        UserManageFxController.userManageFxController.readUserInfo(users);
    }

    /**
     * 通过菜单子项进入主菜单
     * @param actionEvent
     */
    public void enterMainMenuByMenuItem(ActionEvent actionEvent) {
        String text = mainMenu.getText();
        adminSwitchoverMenu.backtrack(ChargingPileManageFxController.class,text);
    }

    /**
     * 点击菜单项的退出项退出系统
     * @param actionEvent
     */
    public void clickExit(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(null);
        alert.setContentText("您确定要退出吗？");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK){
//            Platform.exit();
            exitLogin.backtrack(ChargingPileManageFxController.class);
        }else {
            alert.close();
        }
    }

    /**
     * 读取充电桩列表信息
     * @param chargingPiles
     */
    public void readStationPileInfo(List<ChargingPile> chargingPiles){
        setTableDataAfterSelectAll(chargingPiles);
    }

    /**
     * 查询所有时设置充电桩表格数据
     * @param chargingPiles
     */
    public void setTableDataAfterSelectAll(List<ChargingPile> chargingPiles){
        //转存数据
        for (int i = 0; i < chargingPiles.size(); i++) {
            //转存充电桩id
            Integer oriChargingPileId = chargingPiles.get(i).getId();
            IntegerProperty chargingPileId = new SimpleIntegerProperty(oriChargingPileId);
            //转存所属充电站
            Long oriStationId = chargingPiles.get(i).getStation_id();
            SimpleLongProperty longStationId = new SimpleLongProperty(oriStationId);
            StringProperty stationId = new SimpleStringProperty();
            stationId.set(String.valueOf(longStationId.get()));
            //转存服务电量
            Double oriServicePower = chargingPiles.get(i).getService_charge();
            DoubleProperty servicePower = new SimpleDoubleProperty(oriServicePower);
            //转存充电类型
            Integer oriChargingType = chargingPiles.get(i).getType();
            StringProperty chargingType;
            //将0和1转化为"快充"和"慢充"
            if (oriChargingType==0){
                //充电类型为快充
                String stringChargingType = "快充";
                chargingType = new SimpleStringProperty(stringChargingType);
            }else {
                //充电类型为慢充
                String stringChargingType = "慢充";
                chargingType = new SimpleStringProperty(stringChargingType);
            }
            //转存服务费
            Double oriServiceCharge = chargingPiles.get(i).getPrice();
            SimpleDoubleProperty serviceCharge = new SimpleDoubleProperty(oriServiceCharge);

            //装入数据模型
            data.add(new StationPileData(chargingPileId,stationId,servicePower,chargingType,serviceCharge));
        }

        //对充电站名进行单独处理
        //调用service层查询充电站名
        //查询充电站表信息通过在充电桩表获取充电站id查询
        ChargingDaolmpl chargingDaolmpl = new ChargingDaolmpl();
        List<Charging> chargings = chargingDaolmpl.selectStationBeforeSelectStationPile();
        //获取并设置充电站名
        for (int i = 0; i < chargingPiles.size(); i++) {
            data.get(i).setStationName(chargings.get(i).getStation_name());
        }

        //绑定数据
        tc_pileId.setCellValueFactory(new PropertyValueFactory<StationPileData,Integer>("stationPileId"));
        tc_stationName.setCellValueFactory(cellData -> cellData.getValue().stationNameProperty());
        tc_servicePower.setCellValueFactory(new PropertyValueFactory<StationPileData,Double>("servicePower"));
        tc_chargingType.setCellValueFactory(cellData -> cellData.getValue().chargingTypeProperty());
        tc_serviceCharge.setCellValueFactory(new PropertyValueFactory<StationPileData,Double>("serviceCharge"));
        tableView.setItems(data);
    }

    /**
     * 清空表格中原有的数据
     */
    public void emptyData(){
        //清空原有数据
        for (int i = 0; i < data.size(); i++) {
            data.remove(i);
            i--;
        }
    }

    /**
     * 点击按钮新增数据
     * @param mouseEvent
     */
    public void AddRowData(MouseEvent mouseEvent) {
        //引用fxml样式
        Parent load = null;
        try {
            load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyChargingPileData.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));
        //调用service层查询充电站表获取充电站信息
        ChargingDaolmpl chargingDao = new ChargingDaolmpl();
        List<Charging> chargings = chargingDao.chargingInquire();

        //创建可选择对话框的选项容器
        List<String> choices = new ArrayList<>();
        String defaultChoice = "";
        //添加可选择对话框的选项
        if (chargings.size()>0){
            for (int i = 0; i < chargings.size(); i++) {
                choices.add(chargings.get(i).getStation_name());
                defaultChoice = chargings.get(0).getStation_name();
            }
        }else {
            choices.add("目前还没有充电站供您选择，请先添加");
            defaultChoice = "目前还没有充电站供您选择，请先添加";
        }
        //设置下拉框的选项
        ModifyChargingPileDataFxController.modifyChargingPileDataFxController.setChoiceBoxData(choices);
    }

    /**
     * 点击按钮修改数据
     * @param mouseEvent
     */
    public void updateRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        StationPileData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("修改失败!");
            alert.setContentText("原因：您还没有选择需要修改的行");
            alert.showAndWait();
        }else {
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyChargingPileData.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            ObservableList<Stage> stageList = StageHelper.getStages();
            stageList.get(0).setScene(new Scene(load));
            //调用service层查询充电站表获取充电站信息
            ChargingDaolmpl chargingDao = new ChargingDaolmpl();
            List<Charging> chargings = chargingDao.chargingInquire();

            //创建可选择对话框的选项容器
            List<String> choices = new ArrayList<>();
            String defaultChoice = "";
            //添加可选择对话框的选项
            if (chargings.size()>0){
                for (int i = 0; i < chargings.size(); i++) {
                    choices.add(chargings.get(i).getStation_name());
                    defaultChoice = chargings.get(0).getStation_name();
                }
            }else {
                choices.add("目前还没有充电站供您选择，请先添加");
                defaultChoice = "目前还没有充电站供您选择，请先添加";
            }
            //设置下拉框的选项
            ModifyChargingPileDataFxController.modifyChargingPileDataFxController.setChoiceBoxData(choices);
            //回显原数据
            ModifyChargingPileDataFxController.modifyChargingPileDataFxController.showData(selectedItem);
        }
    }

    /**
     * 点击按钮删除数据
     * @param mouseEvent
     */
    public void deleteRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        StationPileData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("删除失败!");
            alert.setContentText("原因：您还没有选择需要删除的行");
            alert.showAndWait();
        }
        //获取用户想要删除数据的充电桩id
        int stationPileId = selectedItem.getStationPileId();
        //调用service层删除数据
        ChargingPileDaolmpl chargingPileDao = new ChargingPileDaolmpl();
        boolean condition = chargingPileDao.chargingPileDelete(stationPileId);
        if (condition){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText(null);
            alert.setContentText("删除成功!");
            alert.showAndWait();
            //更新数据
            //调用dao层查询充电桩表
            List<ChargingPile> chargingPiles = chargingPileDao.chargingPileInquire();

            //读取充电桩列表信息
            setTableDataAfterDeletedData(chargingPiles);
        }
    }

    /**
     * 删除数据后设置充电站表格数据
     * @param chargingPiles
     */
    public void setTableDataAfterDeletedData(List<ChargingPile> chargingPiles) {
        //清空原有数据
        emptyData();
        //更新数据
        setTableDataAfterSelectAll(chargingPiles);
    }

    /**
     * 关于我们
     * @param actionEvent
     */
    public void aboutUs(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("关于我们");
        alert.setContentText("充电桩管理系统由Power-station项目组人员开发，本管理系统目前已实现四个模块的增删改查。");
        alert.showAndWait();
    }
}
